package leetcode

import kotlinetc.println

//https://leetcode.com/problems/partition-labels/

/**
A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
Note:

S will have length in range [1, 500].
S will consist of lowercase letters ('a' to 'z') only.
 */
fun main(args: Array<String>) {

    //"eccbbbbdec"
    partitionLabels("eccbbbbdec").println()
//    partitionLabels("ababcbacadefegdehijhklij").println()
}


//先记录每个字符的起始终止位置，然后 用双指针，移动，直到指针范围内的字符都 只在指针范围内出现即可
fun partitionLabels(S: String): List<Int> {


    val result = arrayListOf<Int>()

    val sTable = hashMapOf<Char, Int>()
    val eTable = hashMapOf<Char, Int>()

    S.forEachIndexed { index, c ->

        if (sTable.containsKey(c).not())
            sTable[c] = index

        eTable[c] = index
    }


    //双指针查找
    var left = 0
    var right = left
    var end = 0
    while (right < S.length) {


        end = right

        while (right <= end) {
            if (eTable[S[right]]!! > end) {
                end = eTable[S[right]]!!
            }

            right++
        }

        result.add(right - left)

        left = right
    }

    return result
}